package Day11;

import java.util.concurrent.locks.ReentrantLock;

//测试公平锁
public class TestFair {
    //默认是非公平锁          true结束公平锁
    //new NonfairSync()    new FairSync()
    ReentrantLock lock = new ReentrantLock(true);

    public void test() {
        String name = Thread.currentThread().getName();
        try {
            lock.lock();
            System.out.println(name + "获取了锁，开始执行....");
            Thread.sleep(1000);
            System.out.println(name + "执行结束了，释放了锁");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        TestFair fair = new TestFair();
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                while (true) {
                    fair.test();
                }
            }, "线程" + i).start();
        }
    }
}
